package com.cytech.cloudclinic.moudle.main.drug.add.dosage;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.base.BaseFragment;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.event.RefreshDrug;
import com.cytech.cloudclinic.bean.event.UpdateAddTagEvent;
import com.cytech.cloudclinic.bean.req.AddDrugReq;
import com.cytech.cloudclinic.bean.resp.RespDrugDetail;
import com.cytech.cloudclinic.dialog.AddDrugTagDialog;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.yechaoa.yutils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.cytech.cloudclinic.app.Constant.MODE_FREQUENCY_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_MIN_PACKAGE_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_PACKAGE_ID;
import static com.cytech.cloudclinic.app.Constant.MODE_USER_METHOD_ID;

public class AddDrugDosageFragment extends BaseFragment<AddDrugDosagePresenter> implements AddDrugDosageView {


    @BindView(R.id.rv_add_drug_tag)
    RecyclerView rvPackage;
    @BindView(R.id.rv_add_drug_min_package)
    RecyclerView rvMinPackage;
    @BindView(R.id.rv_add_drug_convert_value)
    RecyclerView rvConvertValue;
    @BindView(R.id.rv_add_drug_use)
    RecyclerView rvUse;
    @BindView(R.id.rv_add_drug_frequency)
    RecyclerView rvFrequency;
    @BindView(R.id.rv_add_drug_default_value)
    RecyclerView rvDefaultValue;

    @BindView(R.id.add_drug_tag_convert_value)
    EditText convertValueEt;
    @BindView(R.id.add_drug_tag_default_value)
    EditText defaultValueEt;


    private int drugTagId;
    private int drugId;
    private int parentDrugTagId;
    private List<AddDrugTag> packageList;
    private List<AddDrugTag> minPackageList;
    private List<AddDrugTag> convertList;
    private List<AddDrugTag> userList;
    private List<AddDrugTag> frequencyList;
    private List<AddDrugTag> defaultValueList;

    private AddDrugTagAdapter mPackageAdapter;
    private AddDrugTagAdapter mMinPackageAdapter;
    private AddDrugTagAdapter mConvertAdapter;
    private AddDrugTagAdapter mUseAdapter;
    private AddDrugTagAdapter mFrequencyAdapter;
    private AddDrugTagAdapter mDefaultValueAdapter;

    private AddDrugTagDialog addTagDrugDialog;

    private AddDrugReq drug;

    public static AddDrugDosageFragment newInstance(int drugTagId, int drugId, int parentDrugTagId) {
        AddDrugDosageFragment fragment = new AddDrugDosageFragment();
        //如果有参数，使用Bundle传递
        Bundle bundle = new Bundle();
        bundle.putInt("drugTagId", drugTagId);
        bundle.putInt("drugId", drugId);
        bundle.putInt("parentDrugTagId", parentDrugTagId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected AddDrugDosagePresenter createPresenter() {
        return new AddDrugDosagePresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_add_drug_dosage;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {
        drugTagId = getArguments().getInt("drugTagId");
        drugId = getArguments().getInt("drugId");
        parentDrugTagId = getArguments().getInt("parentDrugTagId");
        drug = (AddDrugReq) getArguments().getSerializable("addDrugReq");

        initPackageRv();
        initMinPackageRv();
        initConvertValueRv();
        initUseRv();
        iniFrequencyRv();
        initDefaultValueRv();

        presenter.getSummaryList(MODE_PACKAGE_ID, parentDrugTagId);

    }

    @Override
    public void getPackageSuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        //获取标签
        mPackageAdapter.setNewInstance(data);
        presenter.getSummaryList(MODE_MIN_PACKAGE_ID, parentDrugTagId);

    }

    @Override
    public void getMinPackageSuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        mMinPackageAdapter.setNewInstance(data);
        presenter.getSummaryList(MODE_USER_METHOD_ID, parentDrugTagId);
    }

    @Override
    public void getUseSuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        mUseAdapter.setNewInstance(data);
        presenter.getSummaryList(MODE_FREQUENCY_ID, parentDrugTagId);
    }

    @Override
    public void getFrequencySuccess(List<AddDrugTag> data) {
        data.add(new AddDrugTag(true));
        mFrequencyAdapter.setNewInstance(data);
        if (drugId != 0) {
            presenter.getDrugDetail(drugId);
        }
    }

    @Override
    public void getDrugDetailSuccess(RespDrugDetail drugDetail) {
        //包装单位
        String parent_unit = drugDetail.parent_unit;
        if(parent_unit!=null){
            List<AddDrugTag> packList = mPackageAdapter.getData();
            for (int i = 0; i < packList.size(); i++) {
                if (parent_unit.equals(packList.get(i).value)) {
                    mPackageAdapter.setCurrentPos(i);
                    break;
                }
            }
        }

        //最小单位
        String subunit = drugDetail.subunit;
        if(subunit!=null){
            List<AddDrugTag> subunitList = mMinPackageAdapter.getData();
            for (int i = 0; i < subunitList.size(); i++) {
                if (subunit.equals(subunitList.get(i).value)) {
                    mMinPackageAdapter.setCurrentPos(i);
                    break;
                }
            }
        }

        //用法
        String usage_mode = drugDetail.usage_mode;
        if(usage_mode!=null){
            List<AddDrugTag> useList = mUseAdapter.getData();
            for (int i = 0; i < useList.size(); i++) {
                if (usage_mode.equals(useList.get(i).value)) {
                    mUseAdapter.setCurrentPos(i);
                    break;

                }
            }
        }

        //频次
        String frequency = drugDetail.frequency;
        if(frequency!=null){
            List<AddDrugTag> frequencyList = mFrequencyAdapter.getData();
            for (int i = 0; i < frequencyList.size(); i++) {
                if (frequency.equals(frequencyList.get(i).value)) {
                    mFrequencyAdapter.setCurrentPos(i);
                    break;
                }
            }
            convertValueEt.setText(String.valueOf(drugDetail.number));
            defaultValueEt.setText(String.valueOf(drugDetail.dosage));
        }
    }

    //初始化包装单位列表
    public void initPackageRv() {
        packageList = new ArrayList<>();
        mPackageAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, packageList);
        rvPackage.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rvPackage.setAdapter(mPackageAdapter);
        mPackageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mPackageAdapter.getItem(position).isAddData) {
                    addTagDrugDialog = new AddDrugTagDialog(MODE_PACKAGE_ID, parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(), "rvPackage");
                } else {
                    mPackageAdapter.setCurrentPos(position);
                }
            }
        });

        mPackageAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (!mPackageAdapter.getItem(position).isAddData) {
                    presenter.delSummaryTag(mPackageAdapter.getItem(position).id);
                    mPackageAdapter.remove(position);
                }
                return false;
            }
        });
    }

    //初始化最小单位列表
    public void initMinPackageRv() {
        minPackageList = new ArrayList<>();
        mMinPackageAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, minPackageList);
        rvMinPackage.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rvMinPackage.setAdapter(mMinPackageAdapter);
        mMinPackageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mMinPackageAdapter.getItem(position).isAddData) {
                    addTagDrugDialog = new AddDrugTagDialog(MODE_MIN_PACKAGE_ID, parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(), "rvMinPackage");
                } else {
                    mMinPackageAdapter.setCurrentPos(position);
                }
            }
        });

        mMinPackageAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (!mMinPackageAdapter.getItem(position).isAddData) {
                    presenter.delSummaryTag(mMinPackageAdapter.getItem(position).id);
                    mMinPackageAdapter.remove(position);
                }
                return false;
            }
        });
    }

    //换算值
    public void initConvertValueRv() {
        convertList = presenter.buildNumValue();
        mConvertAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, convertList);
        rvConvertValue.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rvConvertValue.setAdapter(mConvertAdapter);

        mConvertAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = mConvertAdapter.getItem(position).value;
                convertValueEt.setText(presenter.getRealNumValue(value, convertValueEt.getText().toString()));
            }
        });
    }

    //用法
    public void initUseRv() {
        userList = new ArrayList<>();
        mUseAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, userList);
        rvUse.setLayoutManager(new GridLayoutManager(getActivity(), 6));
        rvUse.setAdapter(mUseAdapter);
        mUseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mUseAdapter.getItem(position).isAddData) {
                    addTagDrugDialog = new AddDrugTagDialog(MODE_USER_METHOD_ID, parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(), "rvUse");
                } else {
                    mUseAdapter.setCurrentPos(position);
                }
            }
        });

        mUseAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (!mUseAdapter.getItem(position).isAddData) {
                    presenter.delSummaryTag(mUseAdapter.getItem(position).id);
                    mUseAdapter.remove(position);
                }
                return false;
            }
        });
    }

    //频次
    public void iniFrequencyRv() {
        frequencyList = new ArrayList<>();
        mFrequencyAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, frequencyList);
        rvFrequency.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        rvFrequency.setAdapter(mFrequencyAdapter);
        mFrequencyAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mFrequencyAdapter.getItem(position).isAddData) {
                    addTagDrugDialog = new AddDrugTagDialog(MODE_FREQUENCY_ID, parentDrugTagId);
                    addTagDrugDialog.show(getFragmentManager(), "rvUse");
                } else {
                    mFrequencyAdapter.setCurrentPos(position);
                }
            }
        });

        mFrequencyAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (!mFrequencyAdapter.getItem(position).isAddData) {
                    presenter.delSummaryTag(mFrequencyAdapter.getItem(position).id);
                    mFrequencyAdapter.remove(position);
                }
                return false;
            }
        });
    }

    public void initDefaultValueRv() {
        defaultValueList = presenter.buildNumValue();
        mDefaultValueAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, defaultValueList);
        rvDefaultValue.setLayoutManager(new GridLayoutManager(getActivity(), 6));
        rvDefaultValue.setAdapter(mDefaultValueAdapter);
        mDefaultValueAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = mDefaultValueAdapter.getItem(position).value;
                defaultValueEt.setText(presenter.getRealNumValue(value, defaultValueEt.getText().toString()));
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateData(UpdateAddTagEvent event) {
        presenter.getSummaryList(event.mode, parentDrugTagId);
    }

    @OnClick(R.id.btn_add_drug_save)
    public void save(View v) {
        if (drug == null) {
            ToastUtil.showToast("请填写基本信息点击下一步");
            return;
        }
        drug.drug_id = drugId;
        drug.parent_unit = mPackageAdapter.getSelectName();
        drug.subunit = mMinPackageAdapter.getSelectName();
        drug.number = ConvertUtils.toDouble(convertValueEt.getText().toString());
        drug.usage_mode = mUseAdapter.getSelectName();
        drug.frequency = mFrequencyAdapter.getSelectName();
        drug.dosage = ConvertUtils.toDouble(defaultValueEt.getText().toString());

        if (TextUtils.isEmpty(drug.parent_unit)) {
            ToastUtil.showToast("请选择包装单位");
            return;
        }
        if (TextUtils.isEmpty(drug.subunit)) {
            ToastUtil.showToast("请选择最小单位");
            return;
        }
        if (drug.number == 0) {
            ToastUtil.showToast("请填写换算值");
            return;
        }
        if (drug.dosage == 0) {
            ToastUtil.showToast("请填写默认用量");
            return;
        }
        presenter.addDrug(drug);
    }

    @Override
    public void addDrugSuccess() {
        EventBus.getDefault().post(new RefreshDrug());
        ToastUtil.showToast("成功");
        getActivity().finish();
    }
}
